﻿using CommonDevelop.Scene;
using CommonEngine;
using Microsoft.Extensions.Caching.Memory;
using System;

namespace CommonDevelop
{
    /// <summary>
    /// 缓存池(场景用户)
    /// </summary>
    public class SceneUserCache
    {
        private static MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());

        public static bool HasCache(string uid)
        {
            return GetCache(uid) != null;
        }

        public static void SetCache(UserInfo en)
        {
            SetCache(en, 8 * 60);
        }

        public static void SetCache(UserInfo en, int expiredMins)
        {
            if (en.IsNull() || en.UserId.IsEmpty())
                return;

            Cache.Set(en.UserId, en.ToJson(), new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromMinutes(expiredMins)
            });
        }

        public static UserInfo GetCache(string uid)
        {
            if (uid.IsEmpty())
                return null;

            if (Cache.TryGetValue(uid, out object val))
                return val.ToString().ToObject<UserInfo>();
            else
                return null;
        }

        public static bool RemoveCache(string uid)
        {
            if (uid.IsEmpty())
                return false;

            try
            {
                Cache.Remove(uid);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        public static bool TryAdd(string Key, string msg)
        {
            if (Key.IsEmpty() || msg.IsEmpty())
                return false;

            Cache.Set(Key, msg, new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromMinutes(30)
            });

            return true;
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        public static string GetData(string Key)
        {
            if (Key.IsEmpty())
                return string.Empty;

            if (Cache.TryGetValue(Key, out object val))
                return val.ToString();
            else
                return string.Empty;
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        public static bool TryRemove(string Key)
        {
            if (Key.IsEmpty())
                return false;

            Cache.Remove(Key);
            return true;
        }
    }
}
